const express = require('express');
const router = express.Router();

// 模拟用户数据
let users = [
  { id: 1, name: '张三', email: 'zhangsan@example.com', role: 'user' },
  { id: 2, name: '李四', email: 'lisi@example.com', role: 'admin' },
  { id: 3, name: '王五', email: 'wangwu@example.com', role: 'user' }
];

// 获取所有用户
router.get('/', (req, res) => {
  res.json({
    status: 'success',
    data: users,
    count: users.length
  });
});

// 获取单个用户
router.get('/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const user = users.find(u => u.id === userId);

  if (!user) {
    return res.status(404).json({
      status: 'error',
      message: '用户不存在'
    });
  }

  res.json({
    status: 'success',
    data: user
  });
});

// 创建新用户
router.post('/', (req, res) => {
  const { name, email, role = 'user' } = req.body;

  // 简单验证
  if (!name || !email) {
    return res.status(400).json({
      status: 'error',
      message: '姓名和邮箱为必填项'
    });
  }

  // 检查邮箱是否已存在
  if (users.some(u => u.email === email)) {
    return res.status(400).json({
      status: 'error',
      message: '邮箱已存在'
    });
  }

  // 创建新用户
  const newUser = {
    id: users.length + 1,
    name,
    email,
    role,
    createdAt: new Date().toISOString()
  };

  users.push(newUser);

  res.status(201).json({
    status: 'success',
    message: '用户创建成功',
    data: newUser
  });
});

// 更新用户
router.put('/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const userIndex = users.findIndex(u => u.id === userId);

  if (userIndex === -1) {
    return res.status(404).json({
      status: 'error',
      message: '用户不存在'
    });
  }

  const { name, email, role } = req.body;

  // 更新用户信息
  if (name) users[userIndex].name = name;
  if (email) users[userIndex].email = email;
  if (role) users[userIndex].role = role;
  users[userIndex].updatedAt = new Date().toISOString();

  res.json({
    status: 'success',
    message: '用户更新成功',
    data: users[userIndex]
  });
});

// 删除用户
router.delete('/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const userIndex = users.findIndex(u => u.id === userId);

  if (userIndex === -1) {
    return res.status(404).json({
      status: 'error',
      message: '用户不存在'
    });
  }

  const deletedUser = users.splice(userIndex, 1)[0];

  res.json({
    status: 'success',
    message: '用户删除成功',
    data: deletedUser
  });
});

module.exports = router;